//
//  UserHomepageViewController.m
//  Fangmm
//
//  Created by 阮琦 on 16/3/4.
//  Copyright © 2016年 com.fangmm. All rights reserved.
//

#import "UserHomepageViewController.h"
#import "JoinRoomPopViewController.h"
#import "TwoButtonsPopViewController.h"
#import "HouseDetailViewController.h"

#import "UserHomepageTitle.h"

#import "UserTeamTableViewCell.h"

#import <SDWebImage/UIImageView+WebCache.h>
#import <SDWebImage/UIButton+WebCache.h>

#import "ACMacros.h"
#import "HttpServer.h"
#import "HomePageUser.h"
#import "User.h"
#import "Team.h"
#import "Seat.h"
#import "WXApi.h"
#import <MobClick.h>

@interface UserHomepageViewController () <UITableViewDataSource, UITableViewDelegate, TwoButtonsViewDelegate>

@end

@implementation UserHomepageViewController {
    id userData;
    HomePageUser *user;
    NSMutableArray *teamsArray;
    NSString *shareUrl;
    WXMediaMessage *shareMessage;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    [self configureNavigationBar];
    [self configureTableView];
    [self loadDatas];
    [self loadShareDatas];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    [self configureNavigationBar];
    [MobClick beginLogPageView:@"个人主页"];
}

- (void)viewWillDisappear:(BOOL)animated {
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    [self.navigationController.navigationBar setBarTintColor:[UIColor whiteColor]];
    NSDictionary *attributes=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor blackColor],NSForegroundColorAttributeName,[UIFont systemFontOfSize:17.0],NSFontAttributeName,nil];
    [self.navigationController.navigationBar setTitleTextAttributes:attributes];
    [MobClick endLogPageView:@"个人主页"];
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark - Configuring the view’s layout behavior
- (void)configureNavigationBar {
    if ([self.userId isEqual:[User sharedUser].userId]) {
        self.title = @"我的主页";
    } else {
        self.title = [NSString stringWithFormat:@"%@的主页",self.userName];
    }
    self.navigationItem.hidesBackButton = true;
    UIImage *backImage = [[UIImage imageNamed:@"back_white"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc]initWithImage:backImage style:UIBarButtonItemStyleDone target:self action:@selector(clickToPopBack)];
    self.navigationItem.leftBarButtonItem = leftBarButton;
    
    UIImage *shareImage = [[UIImage imageNamed:@"share-36-36"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc]initWithImage:shareImage style:UIBarButtonItemStyleDone target:self action:@selector(clickToShare)];
    [rightBarButton setTintColor:RGBACOLOR(119, 119, 119, 1)];
    self.navigationItem.rightBarButtonItem = rightBarButton;
    
    [self.navigationController.navigationBar setBackgroundColor:RGBACOLOR(71, 62, 58, 1)];
    [self.navigationController.navigationBar setBarTintColor:RGBACOLOR(71, 62, 58, 1)];
    
    NSDictionary *attributes=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,[UIFont systemFontOfSize:17.0],NSFontAttributeName,nil];
    [self.navigationController.navigationBar setTitleTextAttributes:attributes];
}

- (void)configureTableView {
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, Main_Screen_Width, Main_Screen_Height - 64)];
    [self.tableView setDelegate:self];
    [self.tableView setDataSource:self];
    [self.tableView setBounces:false];
    [self.tableView setBackgroundColor:RGBACOLOR(240, 240, 240, 1)];
    [self.tableView registerNib:[UINib nibWithNibName:@"UserTeamTableViewCell" bundle:nil] forCellReuseIdentifier:@"UserTeamTableViewCell"];
    [self.view addSubview:self.tableView];
}

- (void)loadDatas {
    [self loadUserWithId:self.userId];
    [self loadUserTeams];
}


- (WXMediaMessage *)wechateShareData:(NSDictionary *)successDic {
    WXMediaMessage *message = [[WXMediaMessage alloc]init];
    [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:[successDic objectForKey:@"thumbnail"]] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
    } completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
        message.thumbData = data;
    }];
    message.title = [successDic objectForKey:@"title"];
    message.description = [successDic objectForKey:@"description"];
    return message;
}

- (void)loadShareDatas {
    if (self.userId == nil || [self.userId isEqual:@""]) {
    } else {
        [HttpServer getSharelinksWithType:@"user" sharedInfo:self.userId WithSuccessBlock:^(NSDictionary *successDic) {
            shareMessage = [self wechateShareData:successDic];
            shareUrl = [successDic objectForKey:@"link"];
        } withFailedBlock:^(id failData) {
            NSLog(@"%@",failData);
        }];
    }
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return 1;
            break;
        case 1:
            return teamsArray.count;
        default:
            return 0;
            break;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;
    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    [cell setBackgroundColor:RGBACOLOR(240, 240, 240, 1)];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    switch (section) {
        case 0:
        {
            UserHomepageTitle *userHomeTitle = [[UserHomepageTitle alloc]init];
            userHomeTitle = [[[NSBundle mainBundle] loadNibNamed:@"UserHomepageTitle" owner:nil options:nil] lastObject];
            [userHomeTitle setFrame:CGRectMake(userHomeTitle.frame.origin.x, userHomeTitle.frame.origin.y, Main_Screen_Width, userHomeTitle.frame.size.height)];
            [userHomeTitle.avatarImage sd_setImageWithURL:[NSURL URLWithString:user.avatar]];
            if (user.name == nil || [user.name isEqual:@""]) {
                user.name = @"未完善";
            }
            [userHomeTitle.nameLabel setText:user.name];
            if ([user.gender isEqualToString:@"f"]) {
                [userHomeTitle.genderImage setImage:[UIImage imageNamed:@"girl_22-22"]];
            } else {
                [userHomeTitle.genderImage setImage:[UIImage imageNamed:@"boy_22-22"]];
            }
            if (user.ageGroup == 0) {
                user.ageGroup = 90;
            }
            if (user.constellation == nil || [user.constellation isEqual:@""]) {
                user.constellation = @"未完善";
            }
            [userHomeTitle.userInfoLabel setText:[NSString stringWithFormat:@"%d后 %@",user.ageGroup, user.constellation]];
            if (user.industry == nil || [user.industry isEqual:@""]) {
                user.industry = @"未完善";
            }
            if (user.constellation == nil || [user.constellation isEqual:@""]) {
                user.constellation = @"未完善";
            }
            [userHomeTitle.userProfessionLabel setText:[NSString stringWithFormat:@"%@-%@",user.industry, user.profession]];
            for (int i = 0; i < user.tags.count; i++) {
                if (user.tags.count <= userHomeTitle.tagLabels.count) {
                    UILabel *label = userHomeTitle.tagLabels[i];
                    [label setText:user.tags[i]];
                }
            }
            if (user.certification) {
                [userHomeTitle.checkImage setImage:[UIImage imageNamed:@"check_ID-44-36"]];
                for (UILabel *label in userHomeTitle.checkLabels) {
                    [label setTextColor:RGBACOLOR(255, 118, 108, 1)];
                    [userHomeTitle.checkLabel setText:@"身份信息已认证通过"];
                }
            } else {
                [userHomeTitle.checkImage setImage:[UIImage imageNamed:@"check_ID_dim-44-36"]];
                for (UILabel *label in userHomeTitle.checkLabels) {
                    [label setTextColor:RGBACOLOR(160, 160, 160, 1)];
                    [userHomeTitle.checkLabel setText:@"身份信息未认证通过"];
                }
            }
            if (user.enterpriseAuth) {
                [userHomeTitle.enterpriseAuthImage setImage:[UIImage imageNamed:@"check_company"]];
                for (UILabel *label in userHomeTitle.enterpriseAuthLabels) {
                    [label setTextColor:RGBACOLOR(255, 118, 108, 1)];
                    [userHomeTitle.enterpriseLabel setText:@"身份信息已认证通过"];
                    
                }
            } else {
                [userHomeTitle.enterpriseAuthImage setImage:[UIImage imageNamed:@"check_company_dim"]];
                for (UILabel *label in userHomeTitle.enterpriseAuthLabels) {
                    [label setTextColor:RGBACOLOR(160, 160, 160, 1)];
                    [userHomeTitle.enterpriseLabel setText:@"企业信息未认证通过"];
                }
            }
            if (user != nil) {
                [cell addSubview:userHomeTitle];
            }
            
            return cell;
        }
            break;
        case 1:
        {
            UserTeamTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UserTeamTableViewCell"];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
            cell.tag = indexPath.row;
            cell.joinButton.tag = indexPath.row;
            Team *team = [[Team alloc] initWithDic:teamsArray[indexPath.row]];
            if ([user.userId isEqualToString:[User sharedUser].userId] || [team.status isEqual:@"full"] || [team.status isEqual:@"success"]) {
                [cell.extraView setHidden:true];
                [cell.joinButton setHidden:true];
            }
            [cell.houseImage sd_setImageWithURL:[NSURL URLWithString:team.houseCover]];
            [cell.houseNameLabel setText:team.houseCommunity];
            NSInteger maxRent = NSIntegerMin;
            NSInteger minRent = NSIntegerMax;
            for (NSDictionary *seatDic in team.seats) {
                Seat *seat = [[Seat alloc]initWithDic:seatDic];
                if (minRent < seat.rent) {
                } else {
                    minRent = seat.rent;
                }
                if (maxRent > seat.rent) {
                } else {
                    maxRent = seat.rent;
                }
            }
            [cell.rentLabel setText:[NSString stringWithFormat:@"¥%ld - ¥%ld",(long)minRent, (long)maxRent]];
            [cell.communityLabel setText:team.houseCommunity];
            [cell.houseCountLabel setText:[NSString stringWithFormat: @"| %d室%d厅%d卫 |",team.houseRoomNum, team.houseHallNum, team.houseToiletNum]];
            [cell.joinButton addTarget:self action:@selector(clickToJoinTeam:) forControlEvents:UIControlEventTouchUpInside];
            [cell.areaLabel setText:[NSString stringWithFormat:@"%dm²",team.houseArea]];
            if (team.houseCheck) {
                cell.checkImage.hidden = false;
                cell.checkLabel.hidden = false;
            } else {
                cell.checkImage.hidden = true;
                cell.checkLabel.hidden = true;
            }
            if ([team.leaderId isEqualToString:self.userId]) {
                [cell.leaderSignLabel setText:@"室长"];
            } else {
                [cell.leaderSignLabel setText:@"室友"];
            }
            return cell;
        }
            break;
        default:
        {
            return cell;
        }
            break;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;
    switch (section) {
        case 0:
            return 210;
            break;
            
        default:
            if ([user.userId isEqualToString:[User sharedUser].userId]) {
                return 140;
            } else {
                return 186;
            }
            break;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        NSInteger row = indexPath.row;
        Team *team = [[Team alloc] initWithDic:teamsArray[row]];
        HouseDetailViewController *houseDetailVC = [[HouseDetailViewController alloc]init];
        houseDetailVC.houseId = team.houseId;
        [self.navigationController pushViewController:houseDetailVC animated:true];
    }
}

#pragma mark - Triggering Methods 
- (void)clickToPopBack {
    [self.navigationController popViewControllerAnimated:true];
}

- (void)clickToShare {
    TwoButtonsPopViewController *twoButtonsVC = [[TwoButtonsPopViewController alloc]initWithNibName:@"TwoButtonsPopViewController" bundle:nil];
    [twoButtonsVC setDelegate:self];
    [self presentViewController:twoButtonsVC animated:true completion:^{
        twoButtonsVC.sourceView = @"Share";
        [twoButtonsVC.titleLabel setText:@"分享个人主页"];
        [twoButtonsVC.firstButton setBackgroundImage:[UIImage imageNamed:@"wechat"] forState:UIControlStateNormal];
        [twoButtonsVC.firstLabel setText:@""];
        [twoButtonsVC.secondButton setBackgroundImage:[UIImage imageNamed:@"fb"] forState:UIControlStateNormal];
        [twoButtonsVC.secondLabel setText:@""];
    }];
}

- (void)clickToJoinTeam:(UIButton *)sender {
    [self loadHouseDetailDataWithTeam:teamsArray[sender.tag]];
}

#pragma mark - Network methods
- (void)loadUserWithId:(NSString *)userId {
    [HttpServer getPersonDetailWithId:userId WithSuccessBlock:^(NSDictionary *successDic) {
        userData = [successDic objectForKey:@"user"];
        user = [[HomePageUser alloc]initWithDic:userData];
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
    } withFailBlock:^(id failData) {
        NSLog(@"%@",failData);
    }];
}

- (void)loadUserTeams {
    [HttpServer getRoomMateTeamWithUserId:self.userId withStatus:@"active" withPage:1 withPageSize:10 withUserInfo:nil withSuccessBlock:^(NSDictionary *successDic) {
        teamsArray =[[NSMutableArray alloc]initWithArray:[successDic objectForKey:@"teams"]];
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationAutomatic];
    } withFailedBlock:^(id failData) {
        NSLog(@"%@",failData);
    }];
}

- (void)loadHouseDetailDataWithTeam:(id)teamData {
    Team *team = [[Team alloc]initWithDic:teamData];
    [HttpServer getHouseDetailWithHouseId:team.houseId WithSuccessBlock:^(NSDictionary *houseData) {
        House *house = [[House alloc]initWithDic:[houseData objectForKey:@"house"]];
        JoinRoomPopViewController *joinRoomVC = [[JoinRoomPopViewController alloc]initWithNibName:@"JoinRoomPopViewController" bundle:nil];
        joinRoomVC.house = house;
        joinRoomVC.teamsData = [NSArray arrayWithObject:teamData];
        [self presentViewController:joinRoomVC animated:true completion:^{
        }];
        } withFailBlock:^(id failData) {
            NSLog(@"%@",failData);
        }];
}

#pragma mark - Two buttons view delegate
- (void)sharebuttonClickedWithTag:(NSInteger)tag {
    SendMessageToWXReq *shareReq = [[SendMessageToWXReq alloc]init];
    shareReq.bText = false;
    shareReq.message = shareMessage;
    WXWebpageObject *webObj = [[WXWebpageObject alloc]init];
    webObj.webpageUrl = shareUrl;
    shareReq.message.mediaObject = webObj;
    switch (tag) {
        case 0:
            shareReq.scene = 0;
            [WXApi sendReq:shareReq];
            [self dismissViewControllerAnimated:true completion:^{
                
            }];
            break;
            
        default:
            shareReq.scene = 1;
            [WXApi sendReq:shareReq];
            [self dismissViewControllerAnimated:true completion:^{
                
            }];
            break;
    }
}
@end
